package net.mujiwulian.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import net.mujiwulian.entity.Banner;
import net.mujiwulian.service.BannerService;
import net.mujiwulian.vo.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @Author: silence
 * @Description:
 * @Date:Create：in 2019/12/30 18:46
 */

@Slf4j
@RestController
@RequestMapping("/banner")
public class BannerController {

    @Value("${file-path}")
    private String filePath;
    private final BannerService bannerService;

    public BannerController(BannerService bannerService) {
        this.bannerService = bannerService;
    }

    @GetMapping("/select")
    public Result<List<Banner>> select(String type) {
        return new Result<>(Result.CodeStatus.OK, "获取轮播图", bannerService.list(new QueryWrapper<Banner>().eq(StringUtils.isNotEmpty(type), "type", type)));
    }


    @PostMapping("/delete")
    public Result<Void> deleteBanner(Integer id) {
        Banner banner = bannerService.getById(id);
        if (banner == null) {
            return new Result<>(Result.CodeStatus.FAIL, "文件不存在");
        }
        File deleteFile = new File(this.filePath + banner.getImgUrl());
        log.warn("删除文件:" + banner.getImgUrl() + "-----" + deleteFile.delete());
        return new Result<>("删除轮播图", bannerService.removeById(id));
    }

    @PostMapping("/insert")
    public Result<Void> insertBanner(Banner banner) {
        if (banner.getImg() == null || StringUtils.isEmpty(banner.getType())) {
            return new Result<>(Result.CodeStatus.FAIL, "参数错误");
        }
        String path = "/files/banner/" + UUID.randomUUID().toString() + banner.getImg().getOriginalFilename();
        banner.setImgUrl(path);
        try {
            log.info("上传文件：" + this.filePath + path);
            FileUtils.copyInputStreamToFile(banner.getImg().getInputStream(), new File(this.filePath + path));
        } catch (IOException e) {
            e.printStackTrace();
            return new Result<>(Result.CodeStatus.FAIL, "网络错误");
        }
        return new Result<>("上传轮播图", bannerService.save(banner));
    }
}
